﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour {
    [SerializeField] private Camera currentCamera;
    [SerializeField] private Transform target;
    [SerializeField] private float monitorWidth = 1;
    [SerializeField] private float monitorHeight= 0.6f;
    /// <summary>
    /// 边界的设定
    /// </summary>
    [SerializeField] private Rect boundary = new Rect (0,0,12.80f,7.20f); 

    private void LateUpdate() {
        FollowTarget();
    }

    private void FollowTarget() {
        if (null == target || null == currentCamera) {
            return;
        }

        Vector3 p1 = currentCamera.transform.position;
        Vector3 p2 = target.position;

        if (p2.x > p1.x + monitorWidth * 0.5f)
            p1.x = p2.x - monitorWidth * 0.5f;
        else if (p2.x < p1.x - monitorWidth * 0.5f)
            p1.x = p2.x + monitorWidth * 0.5f;

        if (p2.y > p1.y + monitorHeight * 0.5f)
            p1.y = p2.y - monitorHeight * 0.5f;
        else if (p2.y < p1.y - monitorHeight * 0.5f)
            p1.y = p2.y + monitorHeight * 0.5f;

        float cameraHeight = currentCamera.orthographicSize;
        float cameraWidth = cameraHeight * currentCamera.aspect;
        if (p1.x + cameraWidth > boundary.width)
            p1.x = boundary.width - cameraWidth;
        else if (p1.x - cameraWidth < boundary.x)
            p1.x = boundary.x + cameraWidth;
        if (p1.y + cameraHeight > boundary.height)
            p1.y = boundary.height - cameraHeight;
        else if (p1.y - cameraHeight < boundary.y)
            p1.y = boundary.y + cameraHeight;

        currentCamera.transform.position = p1;
    }
}
